package com.mi.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mi.bean.AdminInfoBean;
import com.mi.bean.Manager;
import com.mi.service.impl.LoginServiceImpl;
import com.mi.utils.MyUtils;

/**
 * 使用WebServlet注解配置servlet信息 默认参数是servlet的映射路径
 */
@WebServlet("/LoginAction")
public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 对客户端请求进行响应处理
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 业务逻辑处理
		// 设置request编码
		// request.setCharacterEncoding("utf-8");

		// 取出客户端发送的表单数据
		// 将表单数据存入实体bean中进行传输
		Manager managerA = MyUtils.convertFormData2Bean(request, Manager.class);
		
		MyUtils.logRootLogger.info("登录用户名：" + managerA.getManager_name());
		MyUtils.logRootLogger.info("用户密码：" +managerA.getManager_psw());
		// 调用model层进行业务逻辑处理：查询数据库进行用户信息合法性验证
		List<Manager> lstManager = MyUtils.getInstance(LoginServiceImpl.class).queryLoginInfo(managerA);
		// 根据接收到的model的返回结果，进行用户视图的转发控制
		if (lstManager != null && lstManager.size() > 0) {
			// 登录成功，跳转到登录成功的页面
			// 缓存登录成功的用户信息
			
			String strId = lstManager.get(0).getManager_count();
			String strName = lstManager.get(0).getManager_name();
			String strTel = lstManager.get(0).getManager_tel();
			String strEmail = lstManager.get(0).getManager_email();
			String strImg = lstManager.get(0).getManager_img();
			
			// 将用户名存储到session中
			request.getSession().setAttribute("mid", strId);
			request.getSession().setAttribute("mname", strName); //session设值	
			request.getSession().setAttribute("mtel", strTel);   //session设值	
			request.getSession().setAttribute("memail", strEmail);
			request.getSession().setAttribute("mimg", strImg);
			
			request.getSession().setAttribute("loginedManagerUser", lstManager.get(0));
			//response.setCharacterEncoding("utf-8");
			//使用转发
			request.getRequestDispatcher("WEB-INF/logined/main.jsp").forward(request, response);
			// 使用重定向
			//response.sendRedirect("logined/main.jsp");
		} else {
			// 登录失败，重新登录
			// 使用转发
			request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response);
		}
	}

}
